﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarseerGames.FarseerPhysics.Dynamics.Joints;
using FarseerGames.FarseerPhysics.Mathematics;

namespace FreeGoo.GameEngine.Renderables.Links
{
    public class PinJointLink : Link
    {
        public PinJointLink(ILinkable linkable1, ILinkable linkable2, ILinkable owningLinkable)
            : base(linkable1, linkable2, owningLinkable)
        {
        }

        public PinJoint PinJoint { get { return Joint as PinJoint; } }
        public override float TargetDistance { get { return PinJoint.TargetDistance; } set { PinJoint.TargetDistance = value; } }

        public override Vector2 LinkStart { get { return Linkable1.Body.GetWorldPosition(PinJoint.Anchor1); } }
        public override Vector2 LinkEnd { get { return Linkable2.Body.GetWorldPosition(PinJoint.Anchor2); } }
        
        public override float DistanceToPoint(Vector2 point)
        {
            // This isn't 100% accurate, because WorldAnchor refers to the previous timestep, but we'll live with the
            // tiny inaccuracy to save up on some computations...
            return Calculator.DistanceBetweenPointAndLineSegment(point, PinJoint.WorldAnchor1, PinJoint.WorldAnchor2);
        }

        protected override void CreateJoint()
        {
            Joint = new PinJoint(Linkable1.Body, Linkable1.BodyLinkAnchor, Linkable2.Body, Linkable2.BodyLinkAnchor);
            Joint.Tag = this;
        }
    }
}
